package net.xdclass.config;

import feign.RequestInterceptor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Classname AppConfig
 * @Description TODO
 * @Date 2022/4/24 11:17
 * @Created by sunhao
 */
@Slf4j
@ConfigurationProperties(prefix = "spring.redis")
@Configuration
@Data
public class AppConfig {
  private String host;

  private String password;

  private String port;

  private int database;

  @Bean
  public RedissonClient redissonClient(){
    Config config = new Config();
    //单机模式
    config.useSingleServer().setPassword(password).setAddress("redis://"+host+":"+port).setDatabase(database);
    //集群模式
    //config.useClusterServers()
    //.setScanInterval(2000)
    //.addNodeAddress("redis://10.0.29.30:6379", "redis://10.0.29.95:6379")
    // .addNodeAddress("redis://127.0.0.1:6379");
    RedissonClient redisson = Redisson.create(config);
    return redisson;
  }


  @Bean
  public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
    RedisTemplate<String,Object> redisTemplate =  new RedisTemplate<String,Object>();
    redisTemplate.setConnectionFactory(factory);
    StringRedisSerializer redisSerializer = new StringRedisSerializer();
    redisTemplate.setKeySerializer(redisSerializer);
    redisTemplate.setValueSerializer(redisSerializer);
    redisTemplate.setHashKeySerializer(redisSerializer);
    redisTemplate.setHashValueSerializer(redisSerializer);
    return redisTemplate;
  }

  @Bean("requestInterceptor")
  public RequestInterceptor requestInterceptor(){
    return template -> {
      ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
      if(attributes!=null){
        HttpServletRequest request = attributes.getRequest();
        log.info(request.getHeaderNames().toString());
        template.header("token", request.getHeader("token"));
      }else {
        log.warn("requestInterceptor获取Header空指针异常");
      }
    };
  }
}
